package com.example.tranport.client;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.FilterEvent;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;

import java.net.InetSocketAddress;


/****
 * 客户端传输实现
 */
public class ClientTransPortImpl implements ClientTransPort {

    Logger logger = org.slf4j.LoggerFactory.getLogger(ClientTransPortImpl.class);

    //客户端连接器
    private NioSocketConnector acceptor;

    //客户端会话
    private IoSession ioSession;

    //客户端工厂获取配置信息的
    private ClientFactory clientFactory;

    /***
     * 启动服务的客户端
     * @throws Exception
     */
    public void start() throws Exception {
        this.acceptor = new NioSocketConnector();
        this.acceptor.setConnectTimeoutCheckInterval(5000);
        this.acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        this.acceptor.getSessionConfig().setReadBufferSize(1024 * 2);
        this.acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        this.acceptor.setHandler(new IoHandler() {
            @Override
            public void sessionCreated(IoSession ioSession) throws Exception {

            }

            @Override
            public void sessionOpened(IoSession ioSession) throws Exception {
                clientFactory.getClientMessageService().sessionOpened(ioSession);
            }

            @Override
            public void sessionClosed(IoSession ioSession) throws Exception {

            }

            @Override
            public void sessionIdle(IoSession ioSession, IdleStatus idleStatus) throws Exception {

            }

            @Override
            public void exceptionCaught(IoSession ioSession, Throwable throwable) throws Exception {

            }

            @Override
            public void messageReceived(IoSession ioSession, Object o) throws Exception {
                clientFactory.getClientMessageService().messageReceived(ioSession, o);
            }

            @Override
            public void messageSent(IoSession ioSession, Object o) throws Exception {

            }

            @Override
            public void inputClosed(IoSession ioSession) throws Exception {

            }

            @Override
            public void event(IoSession ioSession, FilterEvent filterEvent) throws Exception {

            }
        });
        this.acceptor.addListener(new IoServiceListener() {

            /****
             * 服务端连接成功
             * @param ioService
             * @throws Exception
             */
            @Override
            public void serviceActivated(IoService ioService) throws Exception {

            }

            /****
             * 服务端连接断开，掉线检测
             * @param ioService
             * @param idleStatus
             * @throws Exception
             */
            @Override
            public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception {
            }

            /****
             * 服务端连接断开，掉线检测
             * @param ioService
             * @throws Exception
             */
            @Override
            public void serviceDeactivated(IoService ioService) throws Exception {
                if (!ioService.isDisposed()) {
                    logger.warn("客户端检测: 服务端" + clientFactory.getHost() + ":" + clientFactory.getPort() + "已经掉线，即将重连 ...");
                    connect();
                }
            }

            /****
             * 连接建立成功触发事件
             * @param ioSession
             * @throws Exception
             */
            @Override
            public void sessionCreated(IoSession ioSession) throws Exception {

            }

            @Override
            public void sessionClosed(IoSession ioSession) throws Exception {
                clientFactory.getClientMessageService().sessionClosed(ioSession);
            }

            @Override
            public void sessionDestroyed(IoSession ioSession) throws Exception {

            }
        });
        this.connect();
    }

    /***
     * 停止服务的客户端
     * @throws Exception
     */
    public void stop() throws Exception {
        this.disconnect();
    }

    /***
     * 连接到服务端
     */
    @Override
    public void connect() {
        ConnectFuture connectFuture = this.acceptor.connect(new InetSocketAddress(clientFactory.getHost(), clientFactory.getPort())).awaitUninterruptibly();
        if (connectFuture.isConnected()) {
            logger.warn("服务端:" + clientFactory.getHost() + ":" + clientFactory.getPort() + " 连接成功");
        } else {
            logger.warn("服务端:" + clientFactory.getHost() + ":" + clientFactory.getPort() + " 连接失败，即将重连 ...");
            this.connect();
        }
    }

    /****
     * 断开连接
     */
    @Override
    public void disconnect() {
        this.acceptor.dispose();
    }

    /****
     * @return
     */
    public IoSession getIoSession() {
        return this.ioSession;
    }

    public void setIoSession(IoSession ioSession) {
        this.ioSession = ioSession;
    }

    public ClientTransPortImpl(ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }
}
